package com.kusej.gitmanger.form;

import com.intellij.icons.AllIcons;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.kusej.gitmanger.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.*;

import static com.kusej.gitmanger.utils.Global.masterDefault;
import static com.kusej.gitmanger.utils.Global.versionFlag;
import static com.kusej.gitmanger.utils.TimeUtils.dateFormatDefault;

/**
 * 发布分支
 */
public class PublishDialog extends DialogWrapper {
    private Publish publish;
    private JComboBox<String> comboBox;
    private JComboBox<String> comboBoxTarget;
    private final Project project;

    public PublishDialog(@Nullable Project project) {
        super(project, true, IdeModalityType.IDE);
        this.project = project;
        init();
        setTitle("发布分支");
        setSize(500, 400);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        publish = new Publish();
        comboBox = publish.getSourceBranch();
        comboBoxTarget = publish.getTargetBranch();
        initComboBoxData();
        return publish.getContentPanel();
    }

    @Override
    protected void doOKAction() {
        super.doOKAction();
        String descText = publish.getBranchDesc().getText();// 分支描述
        try {
            String sourceBranchName = Objects.requireNonNull(publish.getSourceBranch().getSelectedItem(), "功能分支不可为空").toString();// 源分支，功能分支，一般为feature-xxx
            String targetBranchName = Objects.requireNonNull(publish.getTargetBranch().getSelectedItem(), "主分支不可为空").toString();// 主干分支，一般为master
            boolean selected = publish.getVersionFlag().isSelected();// 是否生成版本号,选中则生成版本号
            PropertiesComponent.getInstance(project).setValue(versionFlag, String.valueOf(selected));// 记住选择，下次默认
            LoadUtils.defaultLoading(project, "checkout " + targetBranchName);
            // 切到主干分支
            GitBranchUtils.checkout(this.project.getBasePath(), targetBranchName);
            boolean normalFlag = true;
            // 从远程更新到本地，功能分支、主干分支，确保分支都是最新的
            if (sourceBranchName.equals(targetBranchName)) {
                // 同一个分支
                normalFlag = false;
                GitBranchUtils.pulls(this.project.getBasePath(), targetBranchName);
            } else {
                GitBranchUtils.pulls(this.project.getBasePath(), targetBranchName, sourceBranchName);
            }
            // 修改主分支pom.xml并提交
            UpdateDescParams build = UpdateDescParams.builder().project(project).descText(descText).msgText(String.format(Global.descTextFormat, descText, sourceBranchName))
                    .toBranch(targetBranchName.replace(Global.remoteFlag, "")).isMaster(true).build();
            String newVersion = FileModifyUtils.updateDescInner(build);
            if (StringUtils.isBlank(newVersion)) {
                newVersion = targetBranchName.replace(Global.remoteFlag, "");
            }
            // 对主分支创建tag
            String tagName = String.format(Global.tagNameFormat, newVersion, dateFormatDefault.format(new Date()));
            GitBranchUtils.createAndPushTag(this.project.getBasePath(), targetBranchName, tagName, descText);
            if (normalFlag) {
                // 更新功能分支
                LoadUtils.defaultLoading(project, "commit " + sourceBranchName);
                GitBranchUtils.checkout(this.project.getBasePath(), sourceBranchName);
                GitBranchUtils.pulls(this.project.getBasePath(), targetBranchName, sourceBranchName);
                build = UpdateDescParams.builder().project(project).msgText(String.format(Global.descTextFormat, tagName, targetBranchName)).toBranch(sourceBranchName.replace(Global.remoteFlag, "")).build();
                FileModifyUtils.updateDescInner(build);
            }
            Messages.showMessageDialog("Success：已合并至主分支，并完成tag创建", "Message", AllIcons.Actions.Commit);
        } catch (Exception e) {
            e.printStackTrace();
            Messages.showErrorDialog(e.getMessage(), "ERROR");
        }
        LoadUtils.closeLoading();
    }

    private void initComboBoxData() {
        try {
            System.out.println("TagCreateDialog.initComboBoxData==>" + this.project.getBasePath());
            List<String> newData = GitBranchUtils.getRemoteBranches(this.project.getBasePath());
            DefaultComboBoxModel<String> newModel = new DefaultComboBoxModel<>(newData.toArray(new String[0]));
            comboBox.setModel(newModel); // 更新 JComboBox 的数据
            // master 分支排第一位
            String master = newData.stream().filter(a -> a.endsWith(masterDefault)).findAny().orElse(null);
            if (master != null) {
                newData.remove(master);
                newData.add(0, master);
            }
            DefaultComboBoxModel<String> newModel2 = new DefaultComboBoxModel<>(newData.toArray(new String[0]));
            comboBoxTarget.setModel(newModel2);
            boolean aBoolean = PropertiesComponent.getInstance(project).getBoolean(versionFlag, true);
            publish.getVersionFlag().setSelected(aBoolean);
        } catch (Exception e) {
            e.printStackTrace();
            Messages.showErrorDialog(e.getMessage(), "ERROR");
        }

    }

}
